﻿using Consul;
using Grpc.Net.Client;
using ProtoBuf.Grpc.Client;
using ProtobufNet.IProtoServices;
using ProtobufNet.Model;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace MicService.GrpcClient
{
    internal class Program
    {
        private static async Task Main(string[] args) 
        {
            #region Consul发现

            string url = "http://GRpcGroupName";
            ConsulClient client = new ConsulClient(s =>
            {
                //s.Address = new Uri("http://127.0.0.1:8500");
                s.Address = new Uri("http://192.168.106.128:8500");
                s.Datacenter = "dc1";
            });
            var response = client.Agent.Services().Result.Response;

            Uri uri = new Uri(url);
            string groupame = uri.Host;
            AgentService agentService = null;

            var serviceDictionary = response.Where(s => s.Value.Service.Equals(groupame, StringComparison.OrdinalIgnoreCase)).ToArray();
            {
                //有多个服务 选择一个 用到负载均衡策略 此处省略策略实现

                agentService = serviceDictionary[0].Value;
            }
            url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}";

            #endregion Consul发现

            #region 连接方式1，原生的Grpc

            //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            ////创建通道
            //var channel = GrpcChannel.ForAddress(url);

            ////创建客户端代理
            //var clienter = new GreeterClient(channel);

            ////服务端调用
            //var reply = await clienter.SayHelloAsync(new HelloRequest { Name = "客户端传参" });

            //Console.WriteLine(reply.Message);

            #endregion 连接方式1，原生的Grpc

            #region 连接方式2，Protobuf-net.Grpc

            GrpcClientFactory.AllowUnencryptedHttp2 = true;
            var grpcchannel = GrpcChannel.ForAddress(url);
            var clienter = grpcchannel.CreateGrpcService<Iprotobuf>();
            var objectTest = await clienter.GetProtoList(
                new ProtobufRequest()
                {
                    RequestInfo = "请求体",
                    RequestName = "请求名称"
                });
            Console.WriteLine(objectTest.ResponseInfo);

            Console.WriteLine(objectTest.ResponseName);

            #endregion 连接方式2，Protobuf-net.Grpc

            Console.ReadLine();
        }
    }
}